﻿using System;
using System.Data.Linq;
using System.Data.Linq.Mapping;
using System.Windows.Media.Imaging;
using System.IO;
using System.Linq;
using System.Windows.Controls;
using System.Collections.Generic;

namespace Organizer.Model
{
    using System.Collections;

    [Table]
    public class Man : Base<Man>
    {
        [Column(IsPrimaryKey = true, DbType = "UniqueIdentifier NOT NULL", CanBeNull = false, AutoSync = AutoSync.OnInsert)]
        public Guid Id { get; private set; }

        [Column(CanBeNull = true)]
        internal Guid _organizationId;
        /// <summary>
        /// Организация в которую входит
        /// </summary>        
        public Organization Organization
        {
            get { return OrganizerDataContext.Instance.GetOrganizationsById(_organizationId); }
            set
            {
                NotifyPropertyChanging(() => this.Organization);
                if (value != null) _organizationId = value.Id;
                NotifyPropertyChanged(() => this.Organization);
            }
        }

        private string _name;
        [Column]
        public string Name
        {
            get { return _name; }
            set
            {
                if (_name == value) return;
                NotifyPropertyChanging(() => this.Name);
                _name = value;
                NotifyPropertyChanged(() => this.Name);
            }
        }

        private string _lastName;
        [Column]
        public string LastName
        {
            get { return _lastName; }
            set
            {
                if (_lastName == value) return;
                NotifyPropertyChanging(() => this.LastName);
                _lastName = value;
                NotifyPropertyChanged(() => this.LastName);
            }
        }

        private string _patronymic;
        [Column]
        public string PatronymicName
        {
            get { return _patronymic; }
            set
            {
                if (_patronymic == value) return;
                NotifyPropertyChanging(() => this.PatronymicName);
                _patronymic = value;
                NotifyPropertyChanged(() => this.PatronymicName);
            }
        }

        public string ShortName 
        { 
            get 
            {
                string res = LastName;
                if (Name != string.Empty)
                {
                    res += " " + Name[0]+".";
                    if (PatronymicName != string.Empty)
                        res += PatronymicName[0] + ".";
                }
                return res;                                            
            } 
        }

        private readonly EntitySet<User> _users;
        [Association(Storage = "_users", OtherKey = "_manId", ThisKey = "Id", DeleteRule = "CASCADE")]
        public EntitySet<User> Users
        {
            get { return _users; }
            set { _users.Assign(value); }
        }

        public Man()
        {
            Id = Guid.NewGuid();
            _users = new EntitySet<User>(AttachUser, DetachUser);
        }
        public Man(string name, string lName, string pName)
            : this()
        {
            Name = name;
            LastName = lName;
            PatronymicName = pName;
        }

        private void AttachUser(User user)
        {
            NotifyPropertyChanging("Users");
            user.Man = this;
        }
        private void DetachUser(User user)
        {
            NotifyPropertyChanging("Users");
            user.Man = null;
        }

        //[Column]
        //private byte[] _foto;

        //public BitmapImage Foto
        //{
        //    get
        //    {
        //        BitmapImage bitmapImage = new BitmapImage();
        //        MemoryStream ms = new MemoryStream(_foto);
        //        bitmapImage.SetSource(ms);
        //        return bitmapImage;
        //    }
        //    set
        //    {
        //        byte[] data;
        //        using (MemoryStream ms = new MemoryStream())
        //        {
        //            WriteableBitmap btmMap = new WriteableBitmap(value);

        //            // write an image into the stream
        //            Extensions.SaveJpeg(btmMap, ms,
        //                value.PixelWidth, value.PixelHeight, 0, 100);

        //            // reset the stream pointer to the beginning
        //            ms.Seek(0, 0);
        //            //read the stream into a byte array
        //            data = new byte[ms.Length];
        //            ms.Read(data, 0, data.Length);
        //        }

        //        if (_foto == data) return;
        //        NotifyPropertyChanging("Foto");
        //        _foto = data;
        //        NotifyPropertyChanged("Foto");
        //    }
        //}

        public string KeyName
        {
            get { return LastName[0].ToString(); }
        }

        public string ManName
        {
            get { return LastName + " " + Name; }
        }

        public static Man Create(Man man)
        {
            var newMan = new Man();
            newMan.Id = man.Id;
            //newMan.Foto = man.Foto;
            newMan.LastName = man.LastName;
            newMan.Name = man.Name;
            newMan.Organization = man.Organization ?? Organization.None;
            newMan.PatronymicName = man.PatronymicName;
            return newMan;
        }

        public class SortByName : IComparer<Man>
        {
            public int Compare(Man x, Man y)
            {
                return x.LastName.CompareTo(y.LastName);
            }
        }

        public static Man None
        {
            get
            {
                return new Man { Id = Guid.Empty, LastName = string.Empty, Name = string.Empty, PatronymicName = string.Empty };
            }
        }
    }
}
